/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the robot4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.hitqz.robot.admin.controller;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.FileAppender;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hitqz.robot.admin.api.entity.SysFile;
import com.hitqz.robot.admin.service.SysFileService;
import com.hitqz.robot.common.core.util.R;
import com.hitqz.robot.common.log.annotation.SysLog;
import com.hitqz.robot.common.security.annotation.Inner;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.archivers.zip.Zip64Mode;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.slf4j.LoggerFactory;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 文件管理
 *
 * @author Luckly
 * @date 2019-06-18 17:18:42
 */
@RestController
@AllArgsConstructor
@RequestMapping("/sys-file")
@Tag(description = "sys-file", name = "文件管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
@Slf4j
public class SysFileController {

	private final SysFileService sysFileService;

	/**
	 * 分页查询
	 * @param page 分页对象
	 * @param sysFile 文件管理
	 * @return
	 */
	@Operation(summary = "分页查询", description = "分页查询")
	@GetMapping("/page")
	public R getSysFilePage(@ParameterObject Page page, @ParameterObject SysFile sysFile) {
		LambdaQueryWrapper<SysFile> wrapper = Wrappers.<SysFile>lambdaQuery()
			.like(StrUtil.isNotBlank(sysFile.getOriginal()), SysFile::getOriginal, sysFile.getOriginal());
		return R.ok(sysFileService.page(page, wrapper));
	}

	/**
	 * 通过id删除文件管理
	 * @param ids id 列表
	 * @return R
	 */
	@Operation(summary = "通过id删除文件管理", description = "通过id删除文件管理")
	@SysLog("删除文件管理")
	@DeleteMapping
	@PreAuthorize("@pms.hasPermission('sys_file_del')")
	public R removeById(@RequestBody Long[] ids) {
		for (Long id : ids) {
			sysFileService.deleteFile(id);
		}
		return R.ok();
	}

	/**
	 * 上传文件 文件名采用uuid,避免原始文件名中带"-"符号导致下载的时候解析出现异常
	 * @param file 资源
	 * @return R(/ admin / bucketName / filename)
	 */
	@PostMapping(value = "/upload")
	@Operation(summary = "上传文件")
	public R upload(@RequestPart("file") MultipartFile file) {
		return sysFileService.uploadFile(file, false);
	}


	@PostMapping(value = "/uploadDir")
	@Operation(summary = "上传文件--根据日期分类")
	public R uploadDir(@RequestPart("file") MultipartFile file) {
		return sysFileService.uploadFile(file, true);
	}

	/**
	 * 获取文件
	 * @param bucket 桶名称
	 * @param fileName 文件空间/名称
	 * @param response
	 * @return
	 */
	@Inner(false)
	@GetMapping("/{bucket}/{fileName}")
	public void file(@PathVariable String bucket, @PathVariable String fileName, HttpServletResponse response) {
		sysFileService.getFile(bucket, fileName, response);
	}

	@Inner(false)
	@GetMapping("/{bucket}/{dir1}/{dir2}/{fileName}")
	public void file(@PathVariable String bucket,
					 @PathVariable String dir1,
					 @PathVariable String dir2,
					 @PathVariable String fileName,
					 HttpServletResponse response) {
		sysFileService.getFile(bucket, dir1 + File.separator +  dir2, fileName, response);
	}

	/**
	 * 获取本地（resources）文件
	 * @param fileName 文件名称
	 * @param response 本地文件
	 */
	@SneakyThrows
	@GetMapping("/local/file/{fileName}")
	public void localFile(@PathVariable String fileName, HttpServletResponse response) {
		ClassPathResource resource = new ClassPathResource("file/" + fileName);
		response.setContentType("application/octet-stream; charset=UTF-8");
		IoUtil.copy(resource.getInputStream(), response.getOutputStream());
	}
	@GetMapping(value = "downLogs")
	@Operation(summary = "下载日志文件", description = "下载日志文件")
	public ResponseEntity<Resource> downloadLogs(@RequestParam(value = "clientId", required = true) String clientId) {
		log.info("Downloading logs request for client " + clientId);
		//if (clientId.equals("server")) {
		//
		//}
		LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
		FileAppender fileAppender = (FileAppender) loggerContext.getLogger("ROOT").getAppender("info");
		if (fileAppender!= null) {
			String logFilePath = System.getProperty("user.dir") + File.separator + fileAppender.getFile().replace("/info.log", "");
			String targetLog = System.getProperty("java.io.tmpdir") + File.separator + "log.zip";
			File targetLogFile = new File(targetLog);
			if (targetLogFile.exists()) {
				targetLogFile.deleteOnExit();
			}
			compressFolderWithCommonsCompress(logFilePath, targetLog);
			targetLogFile = new File(targetLog);
			if (targetLogFile.exists()) {
				HttpHeaders headers = new HttpHeaders();
				headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
				headers.add("Pragma", "no-cache");
				headers.add("Expires", "0");
				headers.add("Content-Disposition", "attachment; filename=\"+ clientId + \"-logs.zip\"");
				FileSystemResource resource = new FileSystemResource(targetLogFile);
				return ResponseEntity.ok()
						.headers(headers)
						.contentLength(targetLogFile.length())
						.contentType(MediaType.APPLICATION_OCTET_STREAM)
						.body(resource);
			}
		}
		return ResponseEntity.notFound().build();
	}


	public static void compressFolderWithCommonsCompress(String sourceFolderPath, String zipFilePath) {
		try (ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(new FileOutputStream(zipFilePath))) {
			zipOut.setUseZip64(Zip64Mode.AsNeeded);
			compressFolderHelperWithCommonsCompress(sourceFolderPath, "", zipOut);
			zipOut.finish();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void compressFolderHelperWithCommonsCompress(String folderPath, String parentPath, ZipArchiveOutputStream zipOut) throws IOException {
		File folder = new File(folderPath);
		if (folder.isDirectory()) {
			File[] files = folder.listFiles();
			if (files!= null) {
				for (File file : files) {
					String filePath = parentPath + file.getName() + "/";
					if (file.isDirectory()) {
						ZipArchiveEntry zipEntry = new ZipArchiveEntry(filePath);
						zipOut.putArchiveEntry(zipEntry);
						zipOut.closeArchiveEntry();
						compressFolderHelperWithCommonsCompress(file.getAbsolutePath(), filePath, zipOut);
					} else {
						compressFileWithCommonsCompress(file, parentPath, zipOut);
					}
				}
			}
		}
	}

	private static void compressFileWithCommonsCompress(File file, String parentPath, ZipArchiveOutputStream zipOut) throws IOException {
		FileInputStream fis = new FileInputStream(file);
		ZipArchiveEntry zipEntry = new ZipArchiveEntry(file, parentPath + file.getName());
		zipOut.putArchiveEntry(zipEntry);
		IoUtil.copy(fis, zipOut);
		zipOut.closeArchiveEntry();
		fis.close();
	}

}



